<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-form :model="form" ref="gys">
          <el-form-item>
            <treeselect
              v-model="form.supplyId"
              :options="supplyOptions"
              :normalizer="normalizer"
              placeholder="请选择客户"
              style="width: 300px"
              :disabled="isLocked"
            />
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="resetting()"
          v-hasPermi="['supermarket:cx:add']"
          style="margin-top: 5px"
          >重置</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAddDd()"
          v-hasPermi="['supermarket:cx:Dd']"
          style="margin-top: 5px"
          >保存订单</el-button
        >
      </el-col>
    </el-row>
    <el-form :model="form" ref="form" :rules="rules">
      <el-table v-loading="loading" :data="cxList">
        <el-table-column
          label="序号"
          align="center"
          type="index"
        ></el-table-column>
        <el-table-column
          label="商品码"
          align="center"
          prop="productCode"
        ></el-table-column>
        <el-table-column label="货位" align="center" prop="whName" />
        <el-table-column label="商品名称" align="center" prop="productName">
        </el-table-column>
        <el-table-column label="批次" align="center" prop="batch" />
        <el-table-column label="规格" align="center" prop="unit" />
        <el-table-column label="库存数量" align="center" prop="stockNum" />
        <el-table-column label="数量" align="center" prop="tSum">
          <template slot-scope="scope">
            <span v-if="!scope.row.isEdit">
              {{ scope.row.tSum }}
            </span>
            <el-form-item v-else prop="tSum">
              <el-input
                v-model="form.tSum"
                placeholder="请输入数量"
                @blur="handleZje"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="建议售价"
          align="center"
          prop="xsPrice"
        ></el-table-column>

        <el-table-column label="单价" align="center">
          <template slot-scope="scope">
            <div v-if="!scope.row.isEdit">
              {{ scope.row.tPrice }}
            </div>
            <el-form-item v-else prop="tPrice">
              <el-input
                v-model="form.tPrice"
                placeholder="请输入价格"
                @blur="handleZje"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="总金额" align="center">
          <template slot-scope="scope">
            <div v-if="!scope.row.isEdit">
              {{ scope.row.tZPrice }}
            </div>
            <el-form v-else :model="form">
              <el-form-item>
                <el-input v-model="form.tZPrice" :disabled="true" />
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          fixed="right"
          width="100"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.isEdit"
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handAdd(scope.row)"
              v-hasPermi="['supermarket:cx:add']"
              >保存</el-button
            >
            <el-popover
              ref="popoverRef"
              placement="right"
              width="300"
              trigger="click"
              v-else
            >
              <el-form
                ref="form1"
                :model="form1"
                :rules="rules"
                label-width="68px"
              >
                <el-form-item label="数量" prop="tSum">
                  <el-input
                    v-model="form1.tSum"
                    placeholder="请输入数量"
                    @blur="handleZje"
                  />
                </el-form-item>
                <el-form-item label="单价" prop="tPrice">
                  <el-input
                    v-model="form1.tPrice"
                    placeholder="请输入单价"
                    @blur="handleZje"
                  />
                </el-form-item>
                <el-form-item label="总金额" prop="tZPrice">
                  <el-input
                    v-model="form1.tZPrice"
                    placeholder="请输入总金额"
                    :disabled="true"
                  />
                </el-form-item>
                <el-button type="primary" @click="updSub()"
                v-hasPermi="['supermarket:cx:edit']"
                >确 定</el-button>
                <el-button type="primary">取消</el-button>
              </el-form>
              <el-button
                slot="reference"
                size="mini"
                type="text"
                icon="el-icon-edit"
                style="margin-right: 10px"
                 v-hasPermi="['supermarket:cx:query']"
                @click="handleUpdate(scope.row)"
                >修改</el-button
              >
            </el-popover>

            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row, scope.$index)"
              v-hasPermi="['supermarket:cx:remove']"
              >删除</el-button
            >
          </template>
        </el-table-column>
        <template slot="append">
      <div style="text-align: center;">
         <el-button type="primary" plain @click="handleAdd" style="margin: 10px 0;"
      >新增商品</el-button>

      </div>
    </template>
      </el-table>
    </el-form>

    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1000px"
      append-to-body
    >
        <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        :inline="true"
        label-width="68px"
      >
        <el-form-item label="商品码" prop="productCode">
          <el-input
            v-model="queryParams.productCode"
            placeholder="请输入商品码"
            clearable
            @keyup.enter.native="handleQuery"
            style="width: 150px;"
          />
        </el-form-item>
        <el-form-item label="商品名称" prop="productName">
          <el-input
            v-model="queryParams.productName"
            placeholder="请输入商品名称"
            clearable
            @keyup.enter.native="handleQuery"
            style="width: 150px;"
          />
        </el-form-item>
             <el-form-item label="货位名称" prop="whName">
          <el-input
            v-model="queryParams.whName"
            placeholder="请输入货位名称"
            clearable
            @keyup.enter.native="handleQuery"
            style="width: 150px;"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        v-loading="loading"
        :data="stockList"
        :row-class-name="tableRowClassName"
      >
       <el-table-column type="index" align="center" label="序号" />
        <el-table-column label="货位" align="center" prop="whName" />
        <el-table-column label="批次" align="center" prop="batch" />
        <el-table-column label="商品名称" align="center" prop="productName" />
        <el-table-column label="商品码" align="center" prop="productCode" />
        <el-table-column label="规格" align="center" prop="unit" />
        <el-table-column label="库存数量" align="center" prop="stockNum" />
        <el-table-column label="入库采购价" align="center" prop="cjPrice" />
        <el-table-column label="库存总金额" align="center" prop="stockPrice" />
        <el-table-column
          label="生产日期"
          align="center"
          prop="manufactureDate"
          width="100px"
        >
          <template slot-scope="scope">
            <span>{{
              parseTime(scope.row.manufactureDate, "{y}-{m}-{d}")
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="过期日期"
          align="center"
          prop="expirationDate"
          width="100px"
        >
          <template slot-scope="scope">
            <span>{{
              parseTime(scope.row.expirationDate, "{y}-{m}-{d}")
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="品牌" align="center" prop="productBrand" />
        <el-table-column label="产地" align="center" prop="countryOfOrigin" />
        <el-table-column label="分类" align="center" prop="categoryName" />
        <el-table-column label="供应商" align="center" prop="supplyName" />
        <el-table-column
          label="选择"
          align="center"
          fixed="left"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-check"
              circle
              @click="changeProduct(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-dialog>
  </div>
</template>

<script>
import { listProduct, getProduct } from "@/api/supermarket/product";
import { listStock } from "@/api/supermarket/stock";
import {
  listCx,
  getCx,
  delCx,
  addCx,
  updateCx,
  batchAddId,
  addDd,
  tempDdCc,
  delAllCx,
  listCxXs,
} from "@/api/supermarket/cx";
import { listSupply, listSupplyGK, getSupply } from "@/api/supermarket/supply";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "Cx",
  components: { Treeselect },
  data() {
    //数量验证
    let validateTsum = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入数量"));
      } else if (!/^[1-9]\d*$/.test(value)) {
        callback(new Error("数量必须为正整数"));
      } else if (parseInt(value) > this.inventory) {
        callback(new Error("数量不能大于库存数量"));
      } else {
        callback();
      }
    };
    //价格验证
    let validateTprice = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入价格"));
      } else if (!/^\d+(\.\d{1,2})?$/.test(value)) {
        callback(new Error("价格必须为数字，且最多精确到小数点后两位"));
      } else {
        callback();
      }
    };

    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      isLocked: false,
      //库存数量
      inventory: '',
      // 总条数
      total: 0,
      // 采销表格数据
      cxList: [],
      //供应商数据
      supplyOptions: [],
      stockList: [],
      product: [],
      productByOne: {
        produtCode: "",
        productName: "",
        unit: "",
        cjPrice: "",
      },
      // 弹出层标题
      title: "",
      batch: "",
      // 禁用输入选择的标志位
      disableInput: false,
      // 是否显示弹出层
      open: false,
      //渲染商品中表格

      productCode: "",
      pdata: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productId: null,
        tSum: null,
        tPrice: null,
      },
      // 表单参数
      form: {
        tZpSum: 0,
        tZpZprice: 0.0,
        tZPrice: 0,
      },
      form1: {},
      rules: {
        tSum: [
          { required: true, message: "数量不能为空", trigger: "blur" },
          { validator: validateTsum, trigger: "blur" },
        ],
        tPrice: [
          { required: true, message: "单价不能为空", trigger: "blur" },
          { validator: validateTprice, trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getSupplyList();
    this.getList();
    const data = localStorage.getItem("xsformData");
    if (data) {
      const formData = JSON.parse(data);
      this.form.supplyId = formData.supplyId;
      this.isLocked = formData.isLocked;
    }
  },
  methods: {
    handAdd(row) {
      this.$refs.form.validate((valid) => {
        if (!valid) return false;
        this.form.productId = row.productId;
        this.form.batch = this.batch;
        addCx(this.form).then((res) => {
          this.$modal.msgSuccess("新增成功");
          this.getList();
          this.form.tSum = '';
      this.form.tZPrice = '';
      this.form.tPrice = '';
        });
      });
    },
    //商品列表
    getListProduct() {
      listStock().then((response) => {
        this.stockList = response.rows;
        this.total = response.total;
      });
    },

    //查询cx表
    getList() {
      this.loading = true;
      listCxXs(this.queryParams).then((response) => {
        this.cxList = response.data;
        this.cxList.forEach((item) => {
          this.$set(item, "isEdit", false);
        });
      });
      this.loading = false;
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      getCx(row.tid).then((response) => {
        this.form1 = response.data;
      });
    },
    //修改提交
    updSub() {
      this.$refs.form1.validate((valid) => {
        if (!valid) return false;
        updateCx(this.form1).then((res) => {
          console.log(res);
          this.$modal.msgSuccess("修改成功");
          this.$refs.popoverRef.doClose();
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row, index) {
      let t = index + 1;
      if (row.tid != null) {
        this.$modal
          .confirm("确认是否删除第" + t + "行的数据吗？")
          .then(function () {
            return delCx(row.tid);
          })
          .then(() => {
            this.getList();
            this.$modal.msgSuccess("删除成功");
          })
          .catch(() => {});
      } else {
        //删除最后一行
        this.cxList.pop();
             this.form.tSum = "";
        this.form.tZPrice = "";
        this.form.tPrice = "";
      }
    },
    //---------------------------最新----------------------------------
    //重置表单
    resetting() {
      delAllCx().then((res) => {
        localStorage.removeItem("xsformData");
        this.form.supplyId = null;
        this.isLocked = false;
        this.cxList = [];
      });
    },
    //计算总金额
    handleZje() {
      this.$set(this.form, "tZPrice", this.form.tSum * this.form.tPrice);
      this.$set(this.form1, "tZPrice", this.form1.tSum * this.form1.tPrice);
    },
    //保存订单
    handleAddDd() {
      const data = {
        isType: 3,
        supplyId: this.form.supplyId,
      };
      if (this.cxList.length === 0) {
        this.$modal.msgError("无商品，请添加采购商品");
      } else if (this.cxList[this.cxList.length - 1].isEdit) {
        this.$modal.msgError("请先保存采购商品，再点击");
      } else {
        this.$confirm("保存此采购订单, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            addDd(data).then((res) => {
                 this.$modal.msgSuccess("'"+res.msg+"'订单保存成功,待审核");
              this.getList();
              this.resetting();
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消",
            });
          });
      }
    },
    //供应商
    getSupplyList() {
      //1 供应商 2客户 3全是
      const type = 2;
      listSupplyGK(type).then((response) => {
        this.supplyOptions = this.handleTree(response.data, "supplyId");
      });
    },
    //供应商
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.supplyId,
        label: node.supplyName,
        children: node.children,
      };
    },
    //弹层商品列表
    handProduct() {
      this.open = true;
      this.title = "商品库存列表"
      this.getListProduct();
    },
    /** 新增按钮操作 */
    handleAdd() {
      if (this.form.supplyId == null) {
        this.$message.error("请选择供应商");
        return;
      }
      this.isLocked = true;
      let formData = {
        supplyId: this.form.supplyId,
        isLocked: true,
      };
      localStorage.setItem("xsformData", JSON.stringify(formData));

      if (this.cxList.length > 0) {
        if (this.cxList[this.cxList.length - 1].isEdit) {
          this.$message.error("请先保存上一行编辑的数据");
          return;
        }
      }

      this.handProduct();
    },
    //添加行
    addRow(row) {
      this.cxList.push({
        xsPrice: row.xsPrice,
        productCode: row.productCode,
        productId: row.productId,
        productName: row.productName,
        whName: row.whName,
        stockNum: row.stockNum,
        batch: row.batch,
        tPrice: "",
        tSum: "",
        unit: row.unit,
        isEdit: true,
      });
    },
    //选择商品赋值
    changeProduct(row) {
      let data = {
        productId: row.productId,
        batch: row.batch,
      };
      tempDdCc(data).then((res) => {
        if (res.code === 98) {
          this.$modal.msgError(res.msg);
        } else {
          if (res.code === 101) {
            this.$modal.msgError(res.msg);
          } else {
              this.addRow(row);
          }
        }
      });
      this.batch = row.batch;
      this.inventory = row.stockNum;
      this.open = false;
    },
    tableRowClassName({ row }) {
      if (row.status === "1") {
        return "danger-row";
      }
      return "";
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getListProduct();
    },
    resetQuery() {
      this.queryParams.productCode = null;
      this.queryParams.productName = null;
      this.handleQuery();
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-table .danger-row {
  background: #ffcccc;
}
</style>